package com.atguigu.gmall.index.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.annotation.GmallCache;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.index.until.DistributedLock;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.guieffect.qual.UI;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
public class IndexService {

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DistributedLock distributedLock;

    @Autowired
    private RedissonClient redissonClient;

    private static final String KEY_PREFIX = "index:cates:";
    private static final String LOCK_PREFIX = "index:cates:lock:";

    public List<CategoryEntity> queryLvllCategories() {

        ResponseVo<List<CategoryEntity>> listResponseVo = this.pmsClient.queryCategoriesByPid(0l);
        return listResponseVo.getData();
    }

    @GmallCache(prefix = KEY_PREFIX, timeout = 259200, random = 14400, lock = LOCK_PREFIX)
    public List<CategoryEntity> queryLvl23CategoriesByPid(Long pid) {
        ResponseVo<List<CategoryEntity>> listResponseVo = this.pmsClient.queryLvl23CategoriesByPid(pid);
        return listResponseVo.getData();
    }

    public List<CategoryEntity> queryLvl23CategoriesByPid2(Long pid) {
        // 1.先查询缓存，如果缓存中命中，则直接返回
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + pid);
        if (StringUtils.isNotBlank(json)) {
            return JSON.parseArray(json, CategoryEntity.class);
        }

        // 为了防止缓存击穿，添加了分布式锁
        RLock fairLock = this.redissonClient.getFairLock(LOCK_PREFIX + pid);
        fairLock.lock();

        try {
            // 在请求获取锁的过程中，可能有其他请求已经把数据放入缓存，此时再次确认缓存是否存在数据
            String json2 = this.redisTemplate.opsForValue().get(KEY_PREFIX + pid);
            if (StringUtils.isNotBlank(json2)) {
                return JSON.parseArray(json2, CategoryEntity.class);
            }

            // 2.如果缓存没有命中，则远程调用并放入缓存
            ResponseVo<List<CategoryEntity>> listResponseVo = this.pmsClient.queryLvl23CategoriesByPid(pid);
            List<CategoryEntity> categoryEntities = listResponseVo.getData();

            if (CollectionUtils.isEmpty(categoryEntities)) {
                // 为了防止缓存穿透，数据即使为null也缓存，缓存时间不超过5min
                this.redisTemplate.opsForValue().set(KEY_PREFIX + pid, JSON.toJSONString(categoryEntities), 5, TimeUnit.MINUTES);
            } else {
                // 为了防止缓存雪崩给缓存时间添加随机值
                this.redisTemplate.opsForValue().set(KEY_PREFIX + pid, JSON.toJSONString(categoryEntities), 90 + new Random().nextInt(10), TimeUnit.DAYS);
            }

            return categoryEntities;
        } finally {
            fairLock.unlock();
        }
    }

    public void testLock() {
        // 加锁
        RLock lock = this.redissonClient.getLock("lock");
        lock.lock();
        try {
            // 执行业务
            String number = this.redisTemplate.opsForValue().get("number");
            if (StringUtils.isBlank(number)) {
                this.redisTemplate.opsForValue().set("number", "1");
            }
            int num = Integer.parseInt(number);

            this.redisTemplate.opsForValue().set("number", String.valueOf(++num));
        } finally {
            // 释放锁 为了防止误删，先判断再删除
            lock.unlock();
        }
    }

    public void testLock3() {
        // 加锁
        String uuid = UUID.randomUUID().toString();
        Boolean flag = this.distributedLock.tryLock("lock", uuid, 30);

        if (flag) {
            try {
                // 执行业务
                String number = this.redisTemplate.opsForValue().get("number");
                if (StringUtils.isBlank(number)) {
                    this.redisTemplate.opsForValue().set("number", "1");
                }
                int num = Integer.parseInt(number);

//                try {
//                    // this.testSubLock(uuid);
//                    TimeUnit.SECONDS.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

                this.redisTemplate.opsForValue().set("number", String.valueOf(++num));
            } finally {
                // 释放锁 为了防止误删，先判断再删除
                this.distributedLock.unlock("lock", uuid);
            }
        }
    }

    public void testSubLock(String uuid) {
        this.distributedLock.tryLock("lock", uuid, 30);

        System.out.println("====================");

        this.distributedLock.unlock("lock", uuid);
    }

    public void testLock2() {
        // 加锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = this.redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
        if (!lock) {
            try {
                // 重试
                Thread.sleep(50);
                this.testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            // this.redisTemplate.expire("lock", 3, TimeUnit.SECONDS);
            // 执行业务
            String number = this.redisTemplate.opsForValue().get("number");
            if (StringUtils.isBlank(number)) {
                this.redisTemplate.opsForValue().set("number", "1");
            }
            int num = Integer.parseInt(number);
            this.redisTemplate.opsForValue().set("number", String.valueOf(++num));

            // 释放锁 为了防止误删，先判断再删除
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] " +
                    "then " +
                    "   return redis.call('del', KEYS[1]) " +
                    "else " +
                    "   return 0 " +
                    "end";
            this.redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList("lock"), uuid);
//            if (StringUtils.equals(uuid, this.redisTemplate.opsForValue().get("lock"))){
//                this.redisTemplate.delete("lock");
//            }
        }
    }

    public void testRead() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.readLock().lock(10, TimeUnit.SECONDS);
        //rwLock.readLock().unlock();
    }

    public void testWrite() {
        RReadWriteLock rwLock = this.redissonClient.getReadWriteLock("rwLock");
        rwLock.writeLock().lock(10, TimeUnit.SECONDS);
    }

    public void testLatch() {
        try {
            RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
            cdl.trySetCount(6);
            cdl.await();

            // TODO：
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void testCountDown() {
        RCountDownLatch cdl = this.redissonClient.getCountDownLatch("cdl");
        // TODO:
        cdl.countDown();
    }
}
